
var divName = "GroupAndKnockoutTableDiv";

/**
 * This builds a groupBet for this groupName , uses the localstorage Map, maps between games and teams , and sends this HTML to the 
 * GroupGameTableDiv
 */
var buildGroupBetTable = function(groupName,propertiesArray,qualifiersArray){
    var numOfGames = 6;
    var realQualifiers = ["Nigeria","Argentina","Brazil","Mexico","Netherlands","Chile","Greece","Colombia","France","Switzerland","Uruguay","Costa Rica"];
    var gamesList = "";
    var listBets ="";
    for(var j = 0 ; j < numOfGames ; j++){
        var mapHome = map(0,propertiesArray[0].groups[j].match_id).home;
        var mapAway = map(0,propertiesArray[0].groups[j].match_id).away;
        
        
        // This makes home and away teams shorter if the name is 2 or 3 length
        var splitHome = mapHome.split(' ');
        if(splitHome.length > 1 && splitHome.length <= 2){
        mapHome = splitHome[0][0] +". "+ splitHome[1];
        }
        
        if(splitHome.length > 2){
        mapHome = splitHome[0];
        }
        
        var splitAway = mapAway.split(' ');
        if(splitAway.length > 1 && splitAway.length <= 2){
        mapAway = splitAway[0][0] +". "+ splitAway[1];
        }
        
        if(splitAway.length > 2){
        mapAway = splitAway[0];
        }
        
        
        gamesList += "<th>"+ mapHome + "<br>"+mapAway +"</th>";

    }
    
          //For every user
    for(var i = 0 ; i < propertiesArray.length ; i++){
        var currentUser = propertiesArray[i].name;
        //Don't take sudo!
        if(currentUser != 'sudo'){
             //Go over all knockout matches and make them in to one row
            listBets += "<tr><td>"+currentUser.substring(0,currentUser.indexOf(' ') + 2) +".</td>";
            
            //Append Qualifiers for each user
            var rankedF = matchQualifierToUser(currentUser,qualifiersArray).rankedFirst;
            var rankedS = matchQualifierToUser(currentUser,qualifiersArray).rankedSecond;
            
            //Mark if the user HIT on these qualifiers
            if(realQualifiers.indexOf(rankedF) > -1){
                rankedF = "<span style='color:green'>"+rankedF+"</span>";
            }
            //Mark if the user HIT on these qualifiers
            if(realQualifiers.indexOf(rankedS) > -1){
                rankedS = "<span style='color:green'>"+rankedS+"</span>";
            }
            
             listBets += "<td><ul style='text-decoration:none'><li>"+ rankedF+"</li>\
             <li>"+rankedS+"</li></ul></td>";
            
           for(var j = 0 ; j < numOfGames ; j++){
             //Append score
             var gotPoints = propertiesArray[i].groups[j].gotPoints;
             
             var putScore ="";
            if(propertiesArray[i].groups[j].score == null){
             //The case where the user never bet on a score
             putScore = "0 - 0";
             }
             else{
               putScore = propertiesArray[i].groups[j].score[0] + " - " + propertiesArray[i].groups[j].score[1];
  
             }
             if(gotPoints){
                 //User has got points for this match
                 putScore = "<span style='background-color:lightgreen; font-weight:bold'>"+propertiesArray[i].groups[j].score[0] + " - " + propertiesArray[i].groups[j].score[1]+"</span>";
             }
               
            listBets += "<td> "+putScore+" </td>";
             }
        //End of user i
        listBets += "</tr>";
        }
       
     }

    
    var tableHTML = "<table class='table table-hover table-striped' id='GroupGameTable'> \
                    <thead>\
                        <tr>\
                            <th style='vertical-align: middle;'> Name </th>\
                            <th style='vertical-align: middle;'> Qualifiers </th>\
                            "+gamesList+"\
                        </tr>\
                    </thead>\
                    <tbody> "+listBets+"\
                    </tbody>\
                </table>";
                document.getElementById("GroupAndKnockoutTableDiv").innerHTML = tableHTML;
                
                return tableHTML;
    
};

/**
 * Builds the table of all users and puts in the divName table
 */
function buildWorldTable(usersArr){
    var listUsers = "";
    for(var i = 1 ; i < usersArr.length ; i++){
        var rank = i;
        //When you get to this client - give a background to the TR
        if(usersArr[i].name == localStorage.getItem('name')){
            usersArr[i].name = "<span style='color:green'> "+usersArr[i].name+"</span>";
            usersArr[i].points = "<span style='color:green'> "+usersArr[i].points+"</span>";
            //usersArr[i].champion = "<span style='color:green'><img src='img/flags/"+usersArr[i].champion+".png'> </span>";
            rank = "<span style='color:green'>"+rank+"</span>";
        }
       listUsers += "<tr><td>"+rank +"</td><td>"+ usersArr[i].name+"</td><td>"+usersArr[i].points+"</td><td><img src='img/flags/"+usersArr[i].champion+".png'></td></tr>";
    }
    var html = "<div><table class='table table-hover table-striped' style='width:100%' id='GroupGameTable'>\
                    <thead>\
                        <tr>\
                            <th style='vertical-align: middle;'> # </th>\
                            <th style='vertical-align: middle;'> Name </th>\
                            <th style='vertical-align: middle;'> pts </th>\
                            <th style='vertical-align: middle;'> champion </th>\
                        </tr>\
                    </thead>\
                    <tbody>\
                         "+listUsers +" \
                        \
                    </tbody>\
                </table></div>";
                document.getElementById("GroupAndKnockoutTableDiv").innerHTML = html;
}

/**
 * Goes in the same place as the rules table - so can't happen during the same time as betting!
 */
function helpTable(){
     var html="<div class='row clearfix' style=',ax-width:35%;float:right;display: inline-block;margin-left: 7%'><table style='width:50%' class='table table-hover table-striped' id='rulesTable'>";
    html += "<th>Yo Mofucka!</th>";
    
    
    //Append Bullseye
    html+= "<tr><td><p>This shit right here - is where you can see where you are compared to the rest of the world!</p> </td></tr>";
    return html;
}

/**
 * Private function that returns {rankedFirst:<> , rankedSecond:<>} for this user
 */
function matchQualifierToUser(user,qualifiersArray){
    for(var i = 0 ; i < qualifiersArray.length ; i++){
        if(qualifiersArray[i].name == user){
           return {rankedFirst:qualifiersArray[i].qualifiers[0].rankedFirst, rankedSecond:qualifiersArray[i].qualifiers[0].rankedSecond};
          
        }
    }
}
/**
 * Builds the table properties and sends it to KnockoutTableDiv
 * @param {Object} level
 * @param {Object} propertiesArray
 */
var buildKnockoutBetTable = function(level,propertiesArray){
    //clearTableArea();
    var numOfGames = propertiesArray[0].knockout.length;
    var gamesList = "";
    var listBets = "";
    //Create game headers for the table and insert them in gameList
    for(var i = 0 ; i < numOfGames ; i++){
        var tempTeams = map(level,propertiesArray[0].knockout[i].match_id);
        gamesList += "<th style='vertical-align: middle;'>"+tempTeams.home + " <br>"+tempTeams.away+"</th>";
        
       


    }
    //For every user
    for(var i = 0 ; i < propertiesArray.length ; i++){
        //Don't take sudo!
        if(propertiesArray[i].name != 'sudo'){
            
         
            
            
             //Go over all knockout matches and make them in to one row
            listBets += "<tr><td>"+propertiesArray[i].name.substring(0,propertiesArray[i].name.indexOf(' ')+2) +".</td>";
           for(var j = 0 ; j < numOfGames ; j++){
               
                   //Take care of people with closed bets
        if(propertiesArray[i].knockout[j].winner == "Winner" || propertiesArray[i].knockout[j].winner == null){
            propertiesArray[i].knockout[j].winner = "<span style='color:red'>Game Closed</span>";
            propertiesArray[i].knockout[j].score = "";
            
        }
        else{
            //Fix the score with the dash
            propertiesArray[i].knockout[j].score = propertiesArray[i].knockout[j].score[0] + " - " + propertiesArray[i].knockout[j].score[1];
        }
               
               //var putScore = propertiesArray[i].knockout[j].score.split(',')[0] + " - " + propertiesArray[i].knockout[j].score.split(',')[1];
             listBets += "<td><ul><li>"+ propertiesArray[i].knockout[j].winner+"</li><li>"+propertiesArray[i].knockout[j].score+"</li></ul></td>";

             }
        //End of user i
        listBets += "</tr>";
        }
       
     }
     
     
                
     var tableHTML = "<table class='table table-hover table-striped' id='KnockoutTable'>\
                         <thead>\
                             <tr>\
                               <th style='vertical-align: middle;'> Name </th> "+gamesList+"\
                             </tr>\
                         </thead>\
                         <tbody>\
                             "+listBets+"\
                         </tbody>\
                     </table>";
                    document.getElementById("GroupAndKnockoutTableDiv").innerHTML = tableHTML;
                    
                    return tableHTML;
};

/**
 * Builds the user table and puts it inside the #userTableDiv - it should already be sorted!
 * @param {Array} users {name:<value>, points:<value>}
 */
var buildUserTable = function(usersArr){
    var listUsers = "";
  
    for(var i = 0 ; i < usersArr.length ; i++){
        var shortName =  usersArr[i].name.split(' ')[0] +  " " + usersArr[i].name.split(' ')[1][0] + ".";
        if(usersArr[i].name.split(' ')[1].length < 1){
            //THANK YOU FUNIS
            shortName = usersArr[i].name.split(' ')[0];
        }
        rank = i+1;
        if(usersArr[i].name == localStorage.getItem('name')){    
            //If its this user - color him green
            shortName = "<span style='color:green'> "+shortName+"</span>";  
            usersArr[i].points = "<span style='color:green'> "+usersArr[i].points+"</span>";
            rank = "<span style='color:green'> "+rank+"</span>";
        }
       listUsers += "<tr><td>"+rank +"</td><td>"+ shortName+"</td><td>"+usersArr[i].points+"</td></tr>";
    }
    var html = "<table class='table table-hover table-striped' id='userTable'>\
                    <thead>\
                        <tr>\
                            <th style='vertical-align: middle'> # </th>\
                            <th style='vertical-align: middle'> Name </th>\
                            <th style='vertical-align: middle'> pts </th>\
                        </tr>\
                    </thead>\
                    <tbody>\
                        <tr> "+listUsers +" \
                        </tr>\
                    </tbody>\
                </table>";
                document.getElementById('userTableDiv').innerHTML = html;
};



/**
 * Gets the users Array and shows all the tournament bets
 * Puts it in the main div
 */
function buildOthersTable(usersArr){
    var listUsers = "";
   // console.log(usersArr.length);
    for(var i = 0 ; i < usersArr.length ; i++){
        if(usersArr[i].name != 'sudo'){
             listUsers += "<tr><td>"+usersArr[i].name +"</td><td><img src='img/flags/"+ usersArr[i].champion+".png'></td><td>"+usersArr[i].kingOfAssists+"</td><td>"+usersArr[i].kingOfGoals+"</td></tr>";
             
        }
        
    }
    var html = "<table class='table table-hover table-striped' id='KnockoutTable'>\
                    <thead>\
                        <tr>\
                            <th style='vertical-align: middle;'> Name </th>\
                            <th style='vertical-align: middle;'> Champion </th>\
                            <th style='vertical-align: middle;'> Top Assister </th>\
                            <th style='vertical-align: middle;'> Golden Boot </th>\
                        </tr>\
                    </thead>\
                    <tbody>\
                        <tr> "+listUsers +" \
                        </tr>\
                    </tbody>\
                </table>";
                document.getElementById("GroupAndKnockoutTableDiv").innerHTML = html;
                
                return html;
}
/**
 * Builds the table for this user
 */
function buildProfileTable(i_matchesArr){
    var groupNames = ["World Cup, Group A","World Cup, Group B","World Cup, Group C","World Cup, Group D","World Cup, Group E","World Cup, Group F","World Cup, Group G","World Cup, Group H"];
    var groups = i_matchesArr.groups;
    var knockouts = i_matchesArr.knockout;
    var quals = i_matchesArr.qualifiers;
    var playerName = i_matchesArr.name;
    
    var othersHTML = buildOthersTable([{name:playerName,kingOfGoals:i_matchesArr.kingOfGoals,kingOfAssists:i_matchesArr.kingOfAssists,champion:i_matchesArr.champion}]);
    
    
    
    
    //This holds all the group tables for this player
    var groupsTableHTML = "";
    var relevantGroups = [];
          var relevantQualifiers = null;
         var index = 0;
    
    
    //Build group tables
    for (var i=0; i < groupNames.length; i++) { 
        
        
           relevantGroups = [];
           relevantQualifiers = null;
          index = 0;
        
        
        //Get only groups needed for this table
       for (var j=0; j < groups.length; j++) {
          if(groups[j].groupName == groupNames[i]){
              relevantGroups.push(groups[j]);
              //Save time - kill after 6 matches have been found
              if(relevantGroups.length == 6){
                  j = groups.length;
              }
          }
             }; 
            
        //Get only the relevant qualifier for THIS group 
        while(relevantQualifiers == null){
            if(quals[index].groupName == groupNames[i]){
                relevantQualifiers = quals[index];
            }
            index++;  
        }
        
     groupsTableHTML += "<br>" + buildGroupBetTable(groupNames[i],[{name:playerName,groups:relevantGroups}],[{name:playerName,qualifiers:[relevantQualifiers]}]);
     
    };
    
    //Take care of knockout tables
    var knockoutTableHTML = "";
    
    //Check to see if this knockout Level is even available!
    var currLevel = localStorage.getItem('currentLevel');
    
    var numOfLevels = 4;
    var relevantKnockout;
    for (var i=numOfLevels; i > 0 ; i--) {
        
        //Show only levels that are relevant
      if(currLevel != 0 && currLevel <= i){
          
      relevantKnockout = [];
      
      for (var j=0; j < knockouts.length; j++) {
        if(knockouts[j].level == i){
            relevantKnockout.push(knockouts[j]);
        }
      };
      
      knockoutTableHTML += buildKnockoutBetTable(i,[{name:playerName, knockout:[relevantKnockout]}]);
      }
      
      
      
    };
    
    
    //Paste all the tables in the div
     document.getElementById("GroupAndKnockoutTableDiv").innerHTML = othersHTML +  groupsTableHTML + knockoutTableHTML;
    
}

/**
 * Goes in Localstorage and returns the two teams in the form of {home:<value> , away:<value>}
 * @param {Object} i_match_id
 */
function map(level,i_match_id){
   var isMapHere = localStorage.getItem(i_match_id);
   
    //Mapping doesn't exist yet
    if(isMapHere == null){
        requestNewMapping(level);
        //TODO: Fix bug - I DONT WANT A CALLBACK!!!!!
 
    }else{
        var homeT =  localStorage.getItem(i_match_id).substring(0,localStorage.getItem(i_match_id).indexOf(','));
        var awayT =  localStorage.getItem(i_match_id).substring(localStorage.getItem(i_match_id).indexOf(',')+1,localStorage.getItem(i_match_id).length);
        return {home:homeT,away:awayT};
    }
  
}
